#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
using namespace std;
int main()
{
    //1. 创建管道
    int fds[2] = {0};
    int n = pipe(fds);//fds:输出型参数
    if (n != 0)
    {
        cerr << "pipe error" << endl;
        return 1;
    }

    //2. 创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        cerr << "fork error" << endl;
        return 2;
    }
    else if(id == 0)
    {
        // 子进程 --> 写
        // 3.关闭不需要的fd,关闭read
        close(fds[0]);

        int cnt = 0;
        int total = 0;
        while(true)
        {
            string message = "h";

            cnt++;
            //fds[1]
            total += ::write(fds[1],message.c_str(),message.size());
            // cnt++;
            cout << "total: " << total << endl; 
            sleep(2);
        }

        exit(0);
    }
    else
    {
        // 父进程 --> 读
        // 3. 关闭不需要的fd，关闭write
        close(fds[1]);

        char buffer[1024];
        while(true)
        {
            sleep(1);
            ssize_t n = ::read(fds[0],buffer,1024);
            if(n > 0)
            {
                buffer[n] = 0;
                cout << " child->father,message: " << buffer << endl;
            }
            else if(n == 0)
            {
                cout << "n:" << n << endl;
                cout << "child quit ??? me too" << endl;
                break;
            }
            close(fds[0]);
            // break;
            cout << endl;
        }
        int status = 0;
        pid_t rid = waitpid(id,&status,0);
        cout << "father wait chid success: " << rid << " exit code "<<
        ((status<<8)&0xFF) << ", exit sig: " << (status & 0x7F) << std::endl;

    }
    return 0;
}
